package main

import (
	"bufio"
	"flag"
	"fmt"
	"github.com/joho/godotenv"
	"log"
	"mock-build/common"
	"net/rpc"
	"os"
	"strings"
)

var serverCmds = []string{
	"sources", //从fedora获取新版本源码包
	"spec",    //更新spec文件 TODO:初步只完成对版本和ChangeLog的更新
	"srpm",    //打包srpm，并放入http服务
	"upload",  //上传tar.xz源码包，更新souces文件
}
var clientCmds = []string{
	"download", //从server中下载srpm包，放入合适的路径
	"mock",     //mock编译
}

func isCmd(text string, cmds []string) bool {
	for _, v := range cmds {
		if v == text {
			return true
		}
	}
	return false
}

func main() {
	var pkg string
	var version string
	var release string
	var srcTar string
	flag.StringVar(&pkg, "pkg", "qt5-qtwebsockets", "package name which nedd to upgrade")
	flag.StringVar(&version, "version", "5.15.11", "target version need to upgrade")
	flag.StringVar(&release, "release", "1", "fedora release need to set for srpm")
	flag.StringVar(&srcTar, "srcTar", "", "new version src tarball")
	flag.Parse()

	if srcTar == "" {
		//使用默认的qt5模块规则
		module := strings.TrimPrefix(pkg, "qt5-")
		srcTar = module + "-everywhere-opensource-src-" + version + ".tar.xz"
	}

	// 连接到服务器
	// 从配置文件中读取服务器ip和port
	err := godotenv.Load(".env")
	if err != nil {
		log.Fatal("Error loading .env file")
	}
	serverIp := os.Getenv("SERVER_IP")
	serverPort := os.Getenv("SERVER_PORT")
	if serverIp == "" || serverPort == "" {
		log.Fatal("Error: wrong ip or port in .env file")
	}
	client, err := rpc.Dial("tcp", serverIp+":"+serverPort)
	if err != nil {
		log.Fatal("dialing:", err)
	}

	scanner := bufio.NewScanner(os.Stdin)
	fmt.Println("Enter command (type 'exit' to quit):")

	//传入命令行参数
	args := common.Args{
		Cmd:     "test",
		WorkDir: "/root/package-build/packages", //TODO: 写入配置文件
		Pkg:     pkg,
		Version: version,
		Release: release,
		SrcTar:  srcTar,
	}

	// 本地参数
	var mock = new(common.Mock)
	mock.Init(&args)
	mock.DIR = "/root"

	dealCmd := func(text string) {
		switch {
		case text == "test":
			{
				arithArgs := common.ArithArgs{
					A: 3,
					B: 4,
				}
				var reply int
				err = client.Call("Arith.Multiply", &arithArgs, &reply)
				if err != nil {
					log.Fatal("Arith.Multiply call error:", err)
				}
				log.Println(arithArgs, reply)
			}
		case isCmd(text, serverCmds):
			{
				// RPC调用
				args.Cmd = text
				var reply string
				err = client.Call("Mock.Call", args, &reply)
				if err != nil {
					log.Fatal("mock error:", err)
				}

			}
		case isCmd(text, clientCmds):
			{
				//本地调用
				switch text {
				case "download":
					{
						err := common.MakeRun(mock, "client", "download")
						if err != nil {
							log.Fatal("download error:", err)
						}
					}
				case "mock":
					{
						err := common.MakeRun(mock, "client", "mock")
						if err != nil {
							log.Fatal("mock error:", err)
						}
					}
				}
			}
		default:
			{
				log.Println("unknown command, you should input a command in [", strings.Join(append(serverCmds, clientCmds...), " | "), "]")
			}
		}
	}

	for scanner.Scan() {
		text := scanner.Text()

		// 检查用户是否输入了'exit'来退出循环
		if text == "exit" {
			break
		} else if text == "auto" {
			cmds := []string{
				"test",
				"sources",
				"spec",
				"srpm",
				"download",
				"mock",
				"upload",
			}
			for _, cmd := range cmds {
				log.Printf("run cmd [%s]\n", cmd)
				dealCmd(cmd)
			}
			log.Printf("upgrade qt5-%s successfully!!!\n", pkg)
			break
		} else {
			dealCmd(text)
		}

	}

	if err := scanner.Err(); err != nil {
		fmt.Println("reading standard input:", err)
	}

}
